// 主商铺界面
import { client } from '../../../request/index.js'
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog'

Page({
  data: {
    ip: getApp().globalData.ip,
    imgIp: getApp().globalData.imgIp,
    exchange_information: null,
    InputValue: '',
    inputShowed: false,
    widthchange: false,
    isResEmptyHidden: true,
    goodsimg: '',
    goodsid: 0,
    goodsname: '',
    exchangeDto: '',
    ename: '',
    show_flag: '',
    gCoin: 0,
    neededgcoin: 0,
    navbarInitTop: 0, //导航栏初始化距顶部的距离
    isFixedTop: false, //是否固定顶部
  },
  //数据更新
  handleReset() {
    this.setData({
      isResEmptyHidden: true,
      inputValue: '',
    })
    this.storeRedemption(this.options)
  },
  //获取输入框输入的值
  onSearch: function (e) {
    let InputValue = e.detail.value
    this.setData({
      InputValue,
    })
    if (InputValue === '') {
      this.handleReset()
    }
  },
  // 查找商品接口
  async searchGoods(options) {
    let goodsname = this.data.InputValue
    let eid = this.data.exchange_information[0].eid
    const getData = await client({
      url: '/exchangegoods/querygoods',
      data: {
        eid: eid,
        goodsname: goodsname,
      },
    })
    console.log('查找商品', getData)
    if (
      getData.data.code === 888 &&
      getData.data.message === '没有搜索到相关商品'
    ) {
      this.setData({
        isResEmptyHidden: false,
      })
    } else {
      Toast.success('搜索成功')
      this.setData({
        exchange_information: getData.data.data,
      })
    }
  },
  // 兑换商品接口
  async exchangegoods(options) {
    let that = this
    const sessId = getApp().globalData.sessionid
    let useId = getApp().globalData.userId
    const getData = await client({
      url: '/exchangegoods/update',
      method: 'PUT',
      data: {
        eid: options.eid,
        ename: options.ename,
        goodsid: options.goodsid,
        goodsname: options.goodsname,
        neededgcoin: options.neededgcoin,
        useId: useId,
      },
    })
    console.log('兑换商品', getData)
  },
  // 兑换按钮触发
  onExchangeButtontap(e) {
    let that = this
    const ename = this.options.ename
    const eid = this.options.eid
    if (getApp().globalData.sessionid === '') {
      getApp().globalData.showLoginDialog = true
      Dialog.alert({
        title: '检测到尚未登录',
        message: '将为您跳转到其它界面进行登录',
      }).then(() => {
        wx.switchTab({
          url: '../../my/my',
        })
      })
    } else {
      Dialog.confirm({
        title: '兑换',
        message: '您确定兑换该商品吗？',
      })
        .then(() => {
          let gcoin = that.data.gCoin
          console.log('兑换按钮点击', e.currentTarget.dataset.shoppinginfor)
          const goodsname = e.currentTarget.dataset.shoppinginfor.goodsname
          const goodsid = e.currentTarget.dataset.shoppinginfor.goodsid
          const neededgcoin = e.currentTarget.dataset.shoppinginfor.neededgcoin
          that.setData({
            eid: eid,
            ename: ename,
            goodsname: goodsname,
            goodsid: goodsid,
            neededgcoin: neededgcoin,
          })
          const shoppingData = {
            eid: eid,
            goodsid: that.data.goodsid,
            goodsname: that.data.goodsname,
            neededgcoin: that.data.neededgcoin,
            ename: ename,
            useId: getApp().globalData.userId,
          }
          if (that.data.neededgcoin > gcoin) {
            Toast.fail('光币不足')
          } else {
            let index = e.currentTarget.dataset.idx
            let sold = that.data.exchange_information[index].goodsselled + 1
            if (sold > that.data.exchange_information[index].goodsamounts) {
              Toast('此商品已兑换完!')
              // return;
            } else {
              Toast.success('兑换成功')
              let goodselld = 'exchange_information[' + index + '].goodsselled'
              //[属性值]修改
              that.setData({
                gCoin: gcoin - shoppingData.neededgcoin,
                [goodselld]: sold,
              })
              // console.log('传的参数',shoppingData);
              that.exchangegoods(shoppingData)
            }
          }
        })
        .catch(() => {
          Dialog.close()
        })
    }
  },
  //搜索优惠券
  onSearchTap() {
    let InputValue = this.data.InputValue
    if (InputValue === '') {
      Toast.fail('输入不能为空')
      return
    }
    this.searchGoods(this.options)
  },
  //页面兑换券数据
  async storeRedemption(options) {
    const sessId = getApp().globalData.sessionid
    const getData = await client({
      url: '/enterprise/querygoods',
      data: {
        eid: options.eid,
      },
    })

    console.log('店铺兑换', getData)
    this.setData({
      show_flag: sessId,
      exchange_information: getData.data.data,
    })
  },
  //用户信息
  async userInformation() {
    const sessId = getApp().globalData.sessionid
    const getData = await client({
      url: '/account/detail',
    })
    console.log('用户信息', getData)
    this.setData({
      gCoin: getData.data.data.gCoin,
      userId: getData.data.data.userId,
    })
  },

  onLoad: function (options) {
    this.storeRedemption(options)
    this.userInformation()
  },

  onShow: function () {
    var that = this
    if (that.data.navbarInitTop == 0) {
      //获取节点距离顶部的距离
      wx.createSelectorQuery()
        .select('#Topbar')
        .boundingClientRect(function (rect) {
          if (rect && rect.top > 0) {
            var navbarInitTop = parseInt(rect.top)
            that.setData({
              navbarInitTop: navbarInitTop,
            })
          }
        })
        .exec()
    }
  },

  onPageScroll: function (e) {
    var that = this
    var scrollTop = parseInt(e.scrollTop) //滚动条距离顶部高度

    //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
    var isSatisfy = scrollTop >= that.data.navbarInitTop ? true : false
    //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
    if (that.data.isFixedTop === isSatisfy) {
      return false
    }

    that.setData({
      isFixedTop: isSatisfy,
      widthchange: isSatisfy,
    })
  },
  // 查看兑换券
  clickImg(e) {
    console.log(e)
    let imgUrl = this.data.ip + e.currentTarget.dataset.url
    wx.previewImage({
      urls: [imgUrl],
      current: '',
      success: function (res) {},
    })
  },

  onPullDownRefresh: function () {
    this.setData({
      isResEmptyHidden: true,
      inputValue: '',
    })
    this.storeRedemption(this.options)
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  onShareAppMessage: function () {},
})
